<?php

namespace door;

class Api
{
    private $sn = '123456';
    private $client;

    public function __construct()
    {
        $this->client = new \GuzzleHttp\Client([
            'base_uri' => 'http://opendoc.andudu.net',
            'timeout' => 5.0,
            'content-type' => 'application/json'
        ]);
    }

    public function getDoorList(int $door_status = null)
    {
        $response = $this->client->post(
            '/door-yard/door-list',
            [
                \GuzzleHttp\RequestOptions::JSON => [
                    'sn' => $this->sn,
                    'door_status' => $door_status
                ]
            ]
        );
        return json_decode($response->getBody()->getContents());
    }

    public function getMemberList(string $sn,int $page = 1,int $per_page = 50)
    {
        $response = $this->client->post(
            '/holder/member-list',
            [
                \GuzzleHttp\RequestOptions::JSON => [
                    'sn' => $this->sn,
                    'page' => $page,
                    'per_page' => $per_page
                ]
            ]
        );
        return json_decode($response->getBody()->getContents());
    }

    /**
     * 参数排序
     * @param array $param
     * @return string
     */
    private function paramSort(array $param)
    {
        ksort($param); //按照键名对关联数组进行升序排序
        $str = '';
        foreach ($param as $key => $val) {
            if (is_array($val)) {
                $str .= $this->paramSort($val);
            } else {
                $str .= "{$key}={$val}&";
            }
        }
        return $str;
    }

    /**
     * 计算签名字符串
     * @param array $param
     * @param string $api_key
     * @return string
     */
    public function sign(array $param, string $api_key)
    {
        unset($param['sign']);
        $str = $this->paramSort($param);
        $str .= "key=" . $api_key;
        return md5($str);
    }
}